<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<title>注册</title>
	<link rel="stylesheet" href="css/bootstrap.min.css">
	<style>
		#update {
			width: 400px;
			margin: 150px auto
		}

		#alert_info {
			margin: 2px;
			padding: 2px;
			text-align: center;
			margin-bottom: 10px;
			display: none
		}
	</style>
	<script src='ajax.js'></script>
	<script>
		window.onload = function () {
			var oBtn = document.getElementById("btn1");
			var oAlert = document.getElementById("alert_info");
			var aInputs = document.getElementsByTagName("input");

			//给提交按钮添加点击
			oBtn.onclick = function () {
				$ajax({
					method: "post",
					url: 'submitUsers.php',
					data: {
						username: aInputs[0].value,
						password: aInputs[1].value,
						id: aInputs[2].value
					},
					success: function (result) {
						var obj = JSON.parse(result);
						if (obj.code) {
							oAlert.className = 'alert alert-danger';
						} else {
							oAlert.className = 'alert alert-success';
							setTimeout(function () {
								location.href = "userlist.html";
							}, 2000);
						}
						oAlert.style.display = 'block';
						oAlert.innerHTML = obj.message;
					},
					error: function (msg) {
						alert(msg);
					}
				})
			}



			var id = valueByName(location.search, "id");

			//发送id到后台php的页面
			$ajax({
				method: "get",
				url: "updateUsers.php",
				data: {
					id: id
				},
				success: function (result) {
					var obj = JSON.parse(result);
					if (!obj.code) {
						var row = JSON.parse(obj.message);
						aInputs[0].value = row.username;
						aInputs[1].value = row.password;
						aInputs[2].value = row.id;
					}
				},
				error: function (msg) {
					alert(msg);
				}
			})

		}




		//name1=value1&name2=value2&name3=value3 
		function valueByName(search, name) {
			var start = search.indexOf(name + "=");
			if (start == -1) {
				return null;
			} else {
				var end = search.indexOf("&", start);
				if (end == -1) {
					end = search.length;
				}

				//提取出想要键值对 name=value
				var str = search.substring(start, end);
				var arr = str.split("=");
				return arr[1];
			}

		}

	</script>
</head>

<body>
	<div class='container'>
		<div class='panel panel-primary' id='update'>
			<div class='panel-heading'>
				修改用户数据
			</div>
			<div class='panel-body'>
				<div class='form-group'>
					<label for="username">用户名：</label>
					<input type="text" name='username' class='form-control'>
				</div>
				<div class='form-group'>
					<label for="password">密码：</label>
					<input type="text" name='password' class='form-control'>
				</div>
				<div class='form-group'>
					<!-- 隐藏表单 -->
					<input type="hidden" name='id' class='form-control'>
				</div>
				<div id='alert_info' class='alert alert-danger'>xxxxx</div>
				<a href="userlist.html">查看用户列表</a>
				<button id='btn1' class='btn btn-primary pull-right'>提交</button>
			</div>
		</div>
	</div>
</body>

</html>